<template>
	<view class="profile-container page-container">

		<!-- 头像设置 -->
		<view class="avatar-section">
			<view class="avatar-item" @click="changeAvatar">
				<text class="avatar-label">头像</text>
				<view class="avatar-right">
					<image :src="$tools.buildUrl(userInfo.avatar_url)" mode="aspectFill" class="avatar-image"></image>
					<u-icon name="arrow-right" size="16" color="#999"></u-icon>
				</view>
			</view>
		</view>

		<!-- 基本信息 -->
		<view class="info-section">
			<view class="info-item" @click="editNickname">
				<text class="info-label">昵称</text>
				<view class="info-right">
					<input v-if="isEditingNickname" class="nickname-edit-input" v-model="tempNickname"
						placeholder="请输入昵称" maxlength="20" @blur="saveNickname" @confirm="saveNickname"
						:focus="isEditingNickname" />
					<text v-else class="info-value">{{ userInfo.nickname || '未设置' }}</text>
					<u-icon v-if="!isEditingNickname" name="arrow-right" size="16" color="#999"></u-icon>
				</view>
			</view>

			<view class="info-item" @click="handlePhoneClick">
				<text class="info-label">手机号</text>
				<view class="info-right">
					<text class="info-value">{{ userInfo.mobile_hidden || '未绑定' }}</text>
					<!-- <text class="bind-text" v-if="!(userInfo.mobile_hidden && userInfo.mobile_hidden!='')">绑定</text> -->
					<u-icon name="arrow-right" size="16" color="#999" @click="changePhone"></u-icon>
				</view>
			</view>

			<view class="info-item" @click="selectGender">
				<text class="info-label">性别</text>
				<view class="info-right">
					<text class="info-value">{{ getGenderText(userInfo.gender) }}</text>
					<u-icon name="arrow-right" size="16" color="#999"></u-icon>
				</view>
			</view>

			<view class="info-item" @click="selectBirthday">
				<text class="info-label">生日</text>
				<view class="info-right">
					<text class="info-value">{{ userInfo.birthday || '未设置' }}</text>
					<u-icon name="arrow-right" size="16" color="#999"></u-icon>
				</view>
			</view>

			<!-- <view class="info-item" @click="selectRegion">
				<text class="info-label">地区</text>
				<view class="info-right">
					<text class="info-value">{{ userInfo.region || '未设置' }}</text>
					<u-icon name="arrow-right" size="16" color="#999"></u-icon>
				</view>
			</view> -->
		</view>

		<!-- 账户安全 -->
		<view class="security-section">
			<view class="section-title">
				<text class="title-text">账户安全</text>
			</view>
			<view class="security-list">
				<view class="security-item" @click="changePassword">
					<view class="security-left">
						<u-icon name="lock" size="20" color="#1c705e"></u-icon>
						<text class="security-label">修改密码</text>
					</view>
					<view class="security-right">
						<text class="bind-status" :class="{ bound: userInfo.has_password_login==='已设置' }">
							{{ userInfo.has_password_login }}
						</text>
						<u-icon name="arrow-right" size="16" color="#999"></u-icon>
					</view>
				</view>

				<view class="security-item" @click="setPayPassword">
					<view class="security-left">
						<u-icon name="lock" size="20" color="#1c705e"></u-icon>
						<text class="security-label">支付密码</text>
					</view>
					<view class="security-right">
						<text class="bind-status" :class="{ bound: userInfo.has_password_secure==='已设置' }">
							{{ userInfo.has_password_secure }}
						</text>
						<u-icon name="arrow-right" size="16" color="#999"></u-icon>
					</view>
				</view>

			</view>
		</view>



		<!-- 性别选择弹窗 -->
		<u-popup :show="genderPopupShow" mode="bottom" border-radius="20" @close="genderPopupShow = false">
			<view class="gender-popup">
				<view class="popup-header">
					<text class="popup-title">选择性别</text>
					<u-icon name="close" size="20" color="#999" @click="genderPopupShow = false"></u-icon>
				</view>
				<view class="gender-list">
					<view class="gender-item" v-for="(item, index) in genderOptions" :key="index"
						@click="selectGenderOption(item.value)">
						<text class="gender-text">{{ item.label }}</text>
						<u-icon name="checkmark" size="20" color="#1c705e"
							v-if="userInfo.gender === item.value"></u-icon>
					</view>
				</view>
			</view>
		</u-popup>

		<!-- 生日选择器 -->
		<u-datetime-picker :show="birthdayPickerShow" v-model="birthdayValue" mode="date" :minDate="70" title="选择生日"
			@confirm="confirmBirthday" @cancel="cancelBirthday"></u-datetime-picker>
	</view>
</template>

<script>
	import {
		mapGetters
	} from 'vuex'

	export default {
		data() {
			return {
				nicknamePopupShow: false,
				genderPopupShow: false,
				birthdayPickerShow: false,
				isEditingNickname: false,
				tempNickname: '',
				birthdayValue: '',
				genderOptions: [{
						label: '男',
						value: 1
					},
					{
						label: '女',
						value: 2
					},
					{
						label: '保密',
						value: 0
					}
				]
			}
		},
		computed: {
			...mapGetters(['isLogin', 'userInfo'])
		},
		methods: {
			// 更换头像
			changeAvatar() {
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['album', 'camera'],
					success: (res) => {
						if (res.tempFilePaths[0]) {
							// 裁剪图片在上传
							uni.navigateTo({
								url: '/pages/user/headimg-cut?tempFilePaths=' + res.tempFilePaths[0]
							})
						}
					}
				})
			},

			// 编辑昵称
			editNickname() {
				if (!this.isEditingNickname) {
					this.tempNickname = this.userInfo.nickname || ''
					this.isEditingNickname = true
				}
			},

			// 保存昵称
			saveNickname() {
				if (!this.tempNickname.trim()) {
					uni.showToast({
						title: '请输入昵称',
						icon: 'none'
					})
					this.tempNickname = this.userInfo.nickname || ''
					this.isEditingNickname = false
					return
				}

				this.$api.user.updateUserBaseInfo({
					info: {
						nickname: this.tempNickname.trim()
					}
				}).then(res => {
					this.userInfo.nickname = this.tempNickname.trim()
					this.$store.dispatch('updateUserInfo', this.userInfo)
					this.isEditingNickname = false
					uni.showToast({
						title: '昵称更新成功',
						icon: 'success'
					})
				})
			},

			// 处理手机号点击
			handlePhoneClick() {
				if (!this.userInfo.mobile_hidden.trim()) {
					// 未绑定手机号，跳转到绑定页面
					this.bindPhone()
				} else {
					// 已绑定手机号，跳转到换绑页面
					this.changePhone()
				}
			},

			// 绑定手机号
			bindPhone() {
				uni.navigateTo({
					url: '/pages/user/bind-phone'
				})
			},

			// 更换手机号
			changePhone() {
				uni.navigateTo({
					url: '/pages/user/change-phone'
				})
			},

			// 选择性别
			selectGender() {
				this.genderPopupShow = true
			},

			// 选择性别选项
			selectGenderOption(value) {
				this.$api.user.updateUserBaseInfo({
					info: {
						gender: value
					}
				}).then(res => {
					this.userInfo.gender = value
					this.$store.dispatch('updateUserInfo', this.userInfo)
					this.genderPopupShow = false
					uni.showToast({
						title: '性别更新成功',
						icon: 'success'
					})
				})
			},

			// 获取性别文本
			getGenderText(gender) {
				const option = this.genderOptions.find(item => item.value === gender)
				return option ? option.label : '未设置'
			},

			// 选择生日
			selectBirthday() {
				// 设置当前生日值，如果没有则使用默认值
				this.birthdayValue = this.userInfo.birthday || ''
				this.birthdayPickerShow = true
			},

			// 确认生日
			confirmBirthday(value) {
				// value 是一个对象，包含 value 属性
				const selectedDate = value.value || value
				// 将时间戳或日期对象转换为 YYYY-MM-DD 格式
				const formattedDate = this.formatDate(selectedDate)

				this.$api.user.updateUserBaseInfo({
					info: {
						birthday: formattedDate
					}
				}).then(res => {
					this.userInfo.birthday = formattedDate
					this.$store.dispatch('updateUserInfo', this.userInfo)
					this.birthdayPickerShow = false
					uni.showToast({
						title: '生日更新成功',
						icon: 'success'
					})
				})
			},

			// 取消生日选择
			cancelBirthday() {
				this.birthdayPickerShow = false
			},

			// 格式化日期
			formatDate(date) {
				if (!date) return ''

				let dateObj
				// 如果是时间戳（数字）
				if (typeof date === 'number') {
					dateObj = new Date(date)
				}
				// 如果是字符串
				else if (typeof date === 'string') {
					// 如果已经是 YYYY-MM-DD 格式，直接返回
					if (/^\d{4}-\d{2}-\d{2}$/.test(date)) {
						return date
					}
					dateObj = new Date(date)
				}
				// 如果是 Date 对象
				else if (date instanceof Date) {
					dateObj = date
				}
				// 其他情况，尝试转换
				else {
					dateObj = new Date(date)
				}

				// 检查日期是否有效
				if (isNaN(dateObj.getTime())) {
					return '1990-01-01'
				}

				// 格式化为 YYYY-MM-DD
				const year = dateObj.getFullYear()
				const month = String(dateObj.getMonth() + 1).padStart(2, '0')
				const day = String(dateObj.getDate()).padStart(2, '0')

				return `${year}-${month}-${day}`
			},

			// 修改密码
			changePassword() {
				uni.navigateTo({
					url: '/pages/user/change-password'
				})
			},

			// 设置支付密码
			setPayPassword() {
				uni.navigateTo({
					url: '/pages/user/pay-password'
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.profile-container {
		background-color: #f8f8f8;
		min-height: 100vh;
	}

	.avatar-section,
	.info-section {
		background-color: #ffffff;
		margin: 20rpx;
		border-radius: 16rpx;
		overflow: hidden;
	}

	.avatar-item,
	.info-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 30rpx 40rpx;
		border-bottom: 2rpx solid #f5f5f5;
	}

	.avatar-item:last-child,
	.info-item:last-child {
		border-bottom: none;
	}

	.avatar-label,
	.info-label {
		font-size: 28rpx;
		color: #333;
	}

	.avatar-right,
	.info-right {
		display: flex;
		align-items: center;
	}

	.avatar-image {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
		margin-right: 16rpx;
	}

	.info-value {
		font-size: 28rpx;
		color: #666;
		margin-right: 16rpx;
	}

	.bind-text {
		font-size: 26rpx;
		color: #1c705e;
		margin-right: 16rpx;
	}

	.security-section {
		background-color: #ffffff;
		margin: 20rpx;
		border-radius: 16rpx;
		padding: 40rpx;
	}

	.section-title {
		margin-bottom: 30rpx;
	}

	.title-text {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}

	.security-list {
		margin-top: 20rpx;
	}

	.security-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 30rpx 0;
		border-bottom: 2rpx solid #f5f5f5;
	}

	.security-item:last-child {
		border-bottom: none;
	}

	.security-left {
		display: flex;
		align-items: center;
	}

	.security-label {
		font-size: 28rpx;
		color: #333;
		margin-left: 16rpx;
	}

	.security-right {
		display: flex;
		align-items: center;
	}

	.bind-status {
		font-size: 26rpx;
		color: #999;
		margin-right: 16rpx;
	}

	.bind-status.bound {
		color: #1c705e;
	}

	.nickname-edit-input {
		flex: 1;
		font-size: 28rpx;
		color: #333;
		text-align: right;
		border: none;
		outline: none;
		background: transparent;
		padding: 0;
		margin-right: 16rpx;
	}

	.gender-popup {
		padding: 40rpx;
	}

	.popup-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 40rpx;
	}

	.gender-list {
		margin-top: 20rpx;
	}

	.gender-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 30rpx 0;
		border-bottom: 2rpx solid #f5f5f5;
	}

	.gender-item:last-child {
		border-bottom: none;
	}

	.gender-text {
		font-size: 28rpx;
		color: #333;
	}
</style>